package com.myway.service.payment.Oceanpayment.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.myway.core.jersey.client.HttpClient;
import com.myway.dao.*;
import com.myway.dto.common.JsonData;
import com.myway.dto.payment.oceanpayment.OceanpaymentParams;
import com.myway.dto.payment.oceanpayment.TravelCustomer;
import com.myway.dto.vo.FlySegmentVo;
import com.myway.pojo.*;
import com.myway.service.payment.Oceanpayment.OceanpaymentServcie;
import com.myway.service.payment.payUtil.DateUtils;
import com.myway.service.payment.payUtil.Encrypt;
import com.myway.service.payment.payUtil.PayConfig;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by qianmi-05 on 2018/8/15.
 */
@Service
public class OceanpaymentServcieImpl implements OceanpaymentServcie {
    @Autowired
    private FlyOrderMapper flyOrderMapper;
    @Autowired
    private FlySegmentMapper flySegmentMapper;
    @Autowired
    private FlyPassengeMapper flyPassengeMapper;
    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private FlyOrderPaymentMapper flyOrderPaymentMapper;
    @Override
    public OceanpaymentParams OceanpaymentToPay(String orderid,String pages) {
        if(StringUtils.isEmpty(orderid)){
            return  null;
        }
        FlyOrder flyOrder = flyOrderMapper.selectByPrimaryKey(Long.parseLong(orderid));
        List<FlySegmentVo> flySegmentList = flySegmentMapper.getFlySegmentByOrderId(orderid);
        List<FlyPassenge> flyPassengeList = flyPassengeMapper.getFlyPassengeByOrderId(orderid);

        OceanpaymentParams oceanpaymentParams=new OceanpaymentParams();
        oceanpaymentParams.setAccount(PayConfig.PAY_OCEANPAYMENT_ACCOUNT);
        oceanpaymentParams.setTerminal(PayConfig.PAY_OCEANPAYMENT_TERMINAL);
       /* StringBuffer signValue=new StringBuffer();
        signValue.append(PayConfig.PAY_OCEANPAYMENT_ACCOUNT);
        signValue.append(PayConfig.PAY_OCEANPAYMENT_TERMINAL);
        signValue.append(PayConfig.PAY_OCEANPAYMENT_BACKURL);
        signValue.append(flyOrder.getOrderId());//订单编码
        signValue.append(flyOrder.getCurrency());//币种
        signValue.append(flyOrder.getTotalPrice());
*/
        String fristName="N/A";
        String lastName="N/A";
        if(flyOrder.getContactName().isEmpty()){
        }else if(flyOrder.getContactName().indexOf("/")<0){
            fristName="N/A";
            lastName=flyOrder.getContactName();
        }else{
            String[] split = flyOrder.getContactName().split("/");
            fristName=split[0];
            String replaceStr = flyOrder.getContactName().replaceAll(split[0], "");
            lastName=replaceStr;
        }
     /*   signValue.append(fristName);
        signValue.append(lastName);
        signValue.append(flyOrder.getContactEmail());
        signValue.append(PayConfig.PAY_OCEANPAYMENT_SECURE_CODE);*/
         /* account+terminal+backUrl+order_number+order_currency+order_am
        ount+billing_firstName+billing_lastName+billing_email+secureCode
*/
        String signValueStr = PayConfig.PAY_OCEANPAYMENT_ACCOUNT + PayConfig.PAY_OCEANPAYMENT_TERMINAL + PayConfig.PAY_OCEANPAYMENT_BACKURL
                +flyOrder.getOrderId()+flyOrder.getCurrency()+flyOrder.getTotalPrice()+fristName+lastName+flyOrder.getContactEmail()+PayConfig.PAY_OCEANPAYMENT_SECURE_CODE;

        String signValue = Encrypt.String2SHA256(signValueStr);
        oceanpaymentParams.setSignValue(signValue);
        oceanpaymentParams.setBackUrl(PayConfig.PAY_OCEANPAYMENT_BACKURL);
        oceanpaymentParams.setNoticeUrl(PayConfig.PAY_OCEANPAYMENT_NOTICEURL);
        oceanpaymentParams.setMethods("Credit Card");
        oceanpaymentParams.setPages(pages.isEmpty()?"0":pages);
        oceanpaymentParams.setOrder_number(flyOrder.getOrderId());
        oceanpaymentParams.setOrder_currency(flyOrder.getOrderCurrenry());
        oceanpaymentParams.setOrder_amount(flyOrder.getTotalPrice()+"");
        oceanpaymentParams.setBilling_firstName(fristName);
        oceanpaymentParams.setBilling_lastName(lastName);
        oceanpaymentParams.setBilling_email(flyOrder.getContactEmail());
        oceanpaymentParams.setBilling_phone(flyOrder.getContactTel());
        oceanpaymentParams.setBilling_country("N/A");
        oceanpaymentParams.setBilling_city("N/A");
        oceanpaymentParams.setBilling_address(flyOrder.getContactAddress());
        oceanpaymentParams.setBilling_zip("N/A");
        Map<String, String> travelMap = getTravelNum(flyPassengeList);
        oceanpaymentParams.setTravel_adult(travelMap.get("travel_adult"));
        oceanpaymentParams.setTravel_child(travelMap.get("travel_child"));
        oceanpaymentParams.setTravel_infant(travelMap.get("travel_infant"));
        oceanpaymentParams.setTravel_customerInfoJson(getTravelCustomerInfoJson(flyPassengeList,flySegmentList,flyOrder));
       // String post = HttpClient.post("https://secure.oceanpayment.com/gateway/indirectservice/test", JSON.toJSONString(oceanpaymentParams), "application/json");
        return oceanpaymentParams;
    }

    /**
     * 退款
     * @param orderid
     * @return
     */
    @Override
    public String OceanpaymentToRefund(String orderid) {
        return null;
    }

    /**
     * 获取成人 儿童  婴儿 数量
     * @param flyPassengeList
     * @return
     */
    public Map<String,String> getTravelNum(List<FlyPassenge> flyPassengeList){
        Map<String,String> map=new HashMap<String,String>();
        if(flyPassengeList.size()==0){
            map.put("travel_adult","0");
            map.put("travel_child","0");
            map.put("travel_infant","0");
            return map;
        }
        int travel_adult=0;
        int travel_child=0;
        int travel_infant=0;
        for (FlyPassenge flyPassenge:flyPassengeList){
            if(!flyPassenge.getPassageType().isEmpty()){
                if(flyPassenge.getPassageType().equals("1")){//成人
                    travel_adult++;
                }else if(flyPassenge.getPassageType().equals("2")){//儿童
                    travel_child++;
                }else if(flyPassenge.getPassageType().equals("3")){//婴儿
                    travel_infant++;
                }
            }
        }
        map.put("travel_adult",travel_adult+"");
        map.put("travel_child",travel_child+"");
        map.put("travel_infant",travel_infant+"");
        return map;
    }


    /**
     * 获取 travel_customerInfoJson信息
     * @param flyPassengeList
     * @param flySegmentList
     * @return
     */
    public String getTravelCustomerInfoJson(List<FlyPassenge> flyPassengeList,List<FlySegmentVo> flySegmentList,FlyOrder flyOrder){
        if(flyPassengeList.size()==0||flySegmentList.size()==0){
            return "";
        }
        JSONObject jsonObject=new JSONObject();
        List<TravelCustomer> travelCustomerList=new ArrayList<TravelCustomer>();

        String travel_completeRoute="";
        String travel_arrivalDate="";
        String travel_arrivalTime="";
        String travel_destinationAirportCode="";
        String travel_flightNumber="";
        String travel_journeyType="";
        String travel_fareClass="";
        String travel_departureDate=DateUtils.formatDateToStr(flySegmentList.get(0).getDepTime(),"yyyy-MM-dd");
        String travel_departureTime=DateUtils.formatDateToStr(flySegmentList.get(0).getDepTime(),"HH:MM");
        String travel_originalAirportCode=flySegmentList.get(0).getDepCode();
        if(!flySegmentList.get(0).getCabinClass().isEmpty()||flySegmentList.get(0).getCabinClass().equals("T")){
            travel_fareClass="1";
        }else{
            travel_fareClass="2";
        }
        if(!flyOrder.getTicketType().isEmpty()||flyOrder.getTicketType().equals("RT")){ //往返
            travel_completeRoute=flySegmentList.get(0).getDepCode()+"-"+flySegmentList.get(0).getArrCode()+"-"+flySegmentList.get(0).getDepCode();
            travel_arrivalDate=DateUtils.formatDateToStr(flySegmentList.get(flySegmentList.size()-1).getArrTime(),"yyyy-MM-dd");
            travel_arrivalTime=DateUtils.formatDateToStr(flySegmentList.get(flySegmentList.size()-1).getArrTime(),"HH:MM");
            travel_destinationAirportCode=flySegmentList.get(flySegmentList.size()-1).getArrCode();
            for (FlySegment flySegment:flySegmentList){
                travel_flightNumber+=flySegment.getFlightNo()+"-";
            }
            if(!travel_flightNumber.isEmpty()){
                travel_flightNumber=travel_flightNumber.substring(0,travel_flightNumber.length()-1);
            }else{
                travel_flightNumber=flySegmentList.get(0).getFlightNo();
            }
            travel_journeyType="1";

        }else {//如果是空就当作是单程
            travel_completeRoute=flySegmentList.get(0).getDepCode()+"-"+flySegmentList.get(0).getArrCode();
            travel_arrivalDate=DateUtils.formatDateToStr(flySegmentList.get(0).getArrTime(),"yyyy-MM-dd");
            travel_arrivalTime=DateUtils.formatDateToStr(flySegmentList.get(0).getArrTime(),"HH:MM");
            travel_destinationAirportCode=flySegmentList.get(0).getArrCode();
            travel_flightNumber=flySegmentList.get(0).getFlightNo();
            travel_journeyType="2";
        }

        for (FlyPassenge flyPassenge:flyPassengeList){
            TravelCustomer customer=new TravelCustomer();
            customer.setTravel_completeRoute(travel_completeRoute);
            customer.setTravel_departureDate(travel_departureDate);
            customer.setTravel_departureTime(travel_departureTime);
            customer.setTravel_arrivalDate(travel_arrivalDate);
            customer.setTravel_arrivalTime(travel_arrivalTime);
            customer.setTravel_originalAirportCode(travel_originalAirportCode);
            customer.setTravel_destinationAirportCode(travel_destinationAirportCode);

            customer.setTravel_airportCount("0");
            customer.setTravel_airportCode("N/A");
            customer.setTravel_airlinesCount("1");
            customer.setTravel_airlinesCode("MJ");
            customer.setTravel_airlinesName("Myway Airlines");
            customer.setTravel_flightNumber(travel_flightNumber);
            customer.setTravel_journeyType(travel_journeyType);
            customer.setTravel_industryType("1");
            customer.setTravel_accountRegistered("2");
            customer.setTravel_fareClass(travel_fareClass);
            customer.setTravel_departureCountry("N/A");
            customer.setTravel_arrivalCountry("N/A");
            customer.setTravel_lastName(flyPassenge.getXingE());
            customer.setTravel_firstName(flyPassenge.getMingE());
            customer.setTravel_customerTitle(flyPassenge.getXingE()+" "+flyPassenge.getMingE());
            customer.setTravel_isFrequentFlyer("2");
            if(!flyPassenge.getCardType().isEmpty()){
                if(flyPassenge.getCardType().equals("NI")){
                    customer.setTravel_certificateType("2");
                }else if(flyPassenge.getCardType().equals("PP")){
                    customer.setTravel_certificateType("1");
                }else{
                    customer.setTravel_certificateType("99");
                }
            }else{
                customer.setTravel_certificateType("99");
            }
            customer.setTravel_certificateNumber(flyPassenge.getCardNo());
            customer.setTravel_certificateExpiryDate("2099-10-10");
            travelCustomerList.add(customer);
        }
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("customer", travelCustomerList);
        jsonObject.put("travel_customerInfoJson",map);
        return jsonObject.toJSONString();
    }






    public int addPaymentInfo(Payment payment,String payType) {
        if(payment==null){
            return -1;
        }
        payment.setPayType(payType);
        return paymentMapper.insertSelective(payment);
    }

    @Override
    @Transactional
    public int addPaymentInfo(String payment_id, String order_number, String order_currency, String order_amount, String methods,String card_number,String order_notes,String payment_status) {
        FlyOrder flyOrder = flyOrderMapper.getFlyOrderById(order_number);
        if(flyOrder==null){
            return  -1;
        }
        Payment payment=new Payment();
        payment.setPaymentNo(payment_id);
        payment.setPayType("OCEANPAY");
        payment.setAction("pay");//机票支付
        payment.setAmount(new BigDecimal(order_amount));
        payment.setPayTime(new Date());
        payment.setCurrency(order_currency);
        payment.setPayer(flyOrder.getContactName());
        payment.setRemark(order_notes);
        payment.setMerchantId("140105");
        payment.setBankId(card_number);
        if(payment_status.equals("1")){
            payment.setPayStatus("PAID");
        }else{
            payment.setPayStatus("FAIL");
        }
        int paymentNum = paymentMapper.insertSelective(payment);
        if(paymentNum>0){
            FlyOrderPayment flyOrderPayment=new FlyOrderPayment();
            flyOrderPayment.setPaymentId(payment.getId());
            flyOrderPayment.setAmount(new BigDecimal(order_amount));
            flyOrderPayment.setOrderNo(flyOrder.getId());
            int insertSelective = flyOrderPaymentMapper.insertSelective(flyOrderPayment);
            if(insertSelective<0){
                return  -1;
            }
        }else{
            return -1;
        }
        return 1;
    }

    @Override
    public int addOrderPaymentInfo(FlyOrderPayment flyOrderPayment) {
        if(flyOrderPayment==null){
            return -1;
        }
        return flyOrderPaymentMapper.insertSelective(flyOrderPayment);
    }

    @Override
    public FlyOrder selectByOrderId(String orderId) {
        if(orderId != null && orderId != ""){
            FlyOrder flyOrder =  flyOrderMapper.getFlyOrderById(orderId);
            return flyOrder;
        }

        return null;
    }


}
